import { Provide, Inject } from '@midwayjs/core';
import * as fs from 'fs';
import * as path from 'path';
import { FileQueryDto, MoveFilesDto, VirtualPathDto } from '../dto/fileCutDto';
import { GraphService } from './graph.service';
import { v4 as uuidv4 } from 'uuid';
@Provide()
export class FileService {

    @Inject()
    graphService: GraphService;
    // 根据目录获取当前目录的子目录，并返回是否为叶子节点（leaf）
    async getDirectoryTree(query: FileQueryDto) {
        const { path: currentPath } = query;
        const rootPath = path.resolve(currentPath);  // 获取当前目录路径

        // 获取目录结构
        const getDirectoryStructure = (dirPath: string) => {
            const items = fs.readdirSync(dirPath);
            const directories: any[] = [];

            for (const item of items) {
                const fullPath = path.join(dirPath, item);

                try {
                    const stat = fs.statSync(fullPath);
                    if (stat.isDirectory()) {
                        const children = fs.readdirSync(fullPath).filter(child => fs.statSync(path.join(fullPath, child)).isDirectory());

                        // 如果当前目录下没有子目录，标记为叶子节点
                        directories.push({
                            label: item,
                            fullPath,
                            leaf: children.length === 0,  // 如果没有子目录则是叶子节点
                            children: []  // 初始为空数组（懒加载）
                        });
                    }
                } catch (error) {
                    console.error(`Skipping inaccessible directory: ${fullPath}`);
                }
            }
            return directories;
        };

        // 获取目录树
        const directoryTree = getDirectoryStructure(rootPath);
        return { directoryTree };
    }

    // 获取文件列表并返回更多详细信息
    async getFilesInDirectory(query: FileQueryDto) {
        const { path: currentPath } = query;
        const directoryPath = path.resolve(currentPath);  // 获取当前目录路径

        try {
            const files = await fs.promises.readdir(directoryPath);
            const fileDetails: any[] = [];

            // 遍历文件并获取详细信息
            for (const file of files) {
                const filePath = path.join(directoryPath, file);
                const stats = await fs.promises.stat(filePath);
                if (stats.isFile()) {
                    console.log(file)
                    const fileInfo = {
                        name: file,
                        size: stats.size, // 文件大小
                        lastModified: stats.mtime, // 最后修改时间
                        extension: path.extname(file), // 文件扩展名
                        created: stats.birthtime, // 文件创建时间
                        path: filePath, // 文件完整路径
                        isReadOnly: !(stats.mode & fs.constants.S_IWUSR), // 判断文件是否为只读
                        permissions: stats.mode.toString(8), // 文件权限
                    };
                    fileDetails.push(fileInfo);
                }
            }

            return { files: fileDetails };
        } catch (error) {
            throw new Error(`Directory ${directoryPath} does not exist or cannot be accessed.`);
        }
    }
    // 生成虚拟路径（根据灌区和日期）
    async generateVirtualPath(query: VirtualPathDto) {
        const { rootPath, irrigationArea, dateTime } = query;

        const date = new Date(dateTime);
        const CST_OFFSET = 8 * 60 * 60 * 1000;  // 中国标准时间（CST）的时间差（UTC +8）
        const cstDate = new Date(date.getTime() + CST_OFFSET);

        const year = cstDate.getFullYear();
        const month = String(cstDate.getMonth() + 1).padStart(2, '0');
        const day = String(cstDate.getDate()).padStart(2, '0');
        const hours = String(cstDate.getHours()).padStart(2, '0');
        const minutes = String(cstDate.getMinutes()).padStart(2, '0');
        const seconds = String(cstDate.getSeconds()).padStart(2, '0');

        const formattedDateTime = `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;

        const virtualPath = path.join(rootPath, irrigationArea, `${formattedDateTime}.zip`);

        try {
            const dirPath = path.dirname(virtualPath);
            await fs.promises.mkdir(dirPath, { recursive: true }); // 异步创建目录
        } catch (error) {
            console.error("Error creating directory for virtual path:", error);
        }

        return { virtualPath };
    }

    // 文件移植功能
    async moveFiles(moveFilesDto: MoveFilesDto) {
        const { files, targetPath } = moveFilesDto;
        let totalFiles = files.length;
        let copiedFiles = 0;

        // 确保目标路径存在
        try {
            await fs.promises.mkdir(targetPath, { recursive: true });  // 异步创建目标路径
        } catch (error) {
            throw new Error(`Failed to create target directory: ${targetPath}`);
        }

        // 开始拷贝文件
        for (const file of files) {
            const sourceFilePath = file.path;  // 获取文件的完整路径
            const targetFilePath = path.resolve(targetPath, path.basename(file.name));  // 获取目标路径

            // 检查文件是否已经存在于目标路径
            try {
                const fileExists = await fs.promises.stat(targetFilePath).catch(() => false);
                if (fileExists) {
                    // 如果文件已经存在，跳过拷贝
                    console.log(`File ${file.name} already exists in the target path`);
                    continue;  // 跳过当前文件
                }

                // 异步复制文件
                await fs.promises.copyFile(sourceFilePath, targetFilePath);
                copiedFiles++;

                // 计算并输出进度
                const progress = (copiedFiles / totalFiles) * 100;
                console.log(`Progress: ${progress.toFixed(2)}%`);
            } catch (error) {
                throw new Error(`Failed to copy file: ${file.name}`);
            }
        }
        console.log(targetPath)
        let index = targetPath.indexOf("/01_正射影像");
        let base_url = targetPath.substring(0, index);
        const taskId = uuidv4();
        console.log(21, taskId,base_url)
        this.graphService.executeGraphByDynamic5(21, taskId,base_url)
        // 复制完成后返回成功消息
        return { message: 'Files successfully copied' };
    }

    // 文件移植功能
    async moveFiles2(moveFilesDto: MoveFilesDto) {
        const { files, targetPath } = moveFilesDto;
        let totalFiles = files.length;
        let copiedFiles = 0;

        // 确保目标路径存在
        try {
            await fs.promises.mkdir(targetPath, { recursive: true });  // 异步创建目标路径
        } catch (error) {
            throw new Error(`Failed to create target directory: ${targetPath}`);
        }

        // 开始拷贝文件
        for (const file of files) {
            const sourceFilePath = file.path;  // 获取文件的完整路径
            const targetFilePath = path.resolve(targetPath, path.basename(file.name));  // 获取目标路径

            // 检查文件是否已经存在于目标路径
            try {
                const fileExists = await fs.promises.stat(targetFilePath).catch(() => false);
                if (fileExists) {
                    // 如果文件已经存在，跳过拷贝
                    console.log(`File ${file.name} already exists in the target path`);
                    continue;  // 跳过当前文件
                }

                // 异步复制文件
                await fs.promises.copyFile(sourceFilePath, targetFilePath);
                copiedFiles++;

                // 计算并输出进度
                const progress = (copiedFiles / totalFiles) * 100;
                console.log(`Progress: ${progress.toFixed(2)}%`);
            } catch (error) {
                throw new Error(`Failed to copy file: ${file.name}`);
            }
        }
        console.log(targetPath)
        let index = targetPath.indexOf("/01_正射影像");
        let base_url = targetPath.substring(0, index);
        const taskId = uuidv4();
        console.log(21, taskId,base_url)
        this.graphService.executeGraphByDynamic5(115, taskId,base_url)
        // 复制完成后返回成功消息
        return { message: 'Files successfully copied' };
    }
}




